<template>
  <div>
    <a-row v-for="(item, index) in props.modelValue" :key="index">
      <a-form-item :label="index === 0 ? '规格' : ''">
        <a-space>
          <a-input v-model="item.name" placeholder="请输入规格" />
          <a-button @click="del(index)">
            <template #icon>
              <icon-close />
            </template>
          </a-button>
        </a-space>
      </a-form-item>
      <a-form-item>
        <a-space wrap>
          <a-tag
            v-for="tag of item.value"
            :key="tag"
            closable
            size="large"
            color="arcoblue"
            @close="handleRemove(tag, item)"
          >
            {{ tag }}
          </a-tag>

          <a-input
            v-if="state[index].showInput"
            ref="inputRef"
            v-model.trim="state[index].inputVal"
            :style="{ width: '90px' }"
            placeholder="规格值"
            @keyup.enter="handleAdd(index, state[index].inputVal)"
            @blur="handleAdd(index, state[index].inputVal)"
          />
          <a-tag
            v-else
            :style="{
              width: '65px',
              backgroundColor: 'var(--color-fill-2)',
              border: '1px dashed var(--color-fill-3)',
              cursor: 'pointer',
            }"
            type="primary"
            size="large"
            @click="handleEdit(index)"
          >
            <template #icon>
              <icon-plus />
            </template>
            添加
          </a-tag>
        </a-space>
      </a-form-item>
    </a-row>
    <a-form-item>
      <a-space>
        <a-button type="primary" @click="add">添加新规格</a-button>
        <a-button @click="table.create">立即生成</a-button>
      </a-space>
    </a-form-item>
    <a-form-item label="批量设置">
      <a-table
        row-key="id"
        :columns="[
          ...table.allColumns,
          {
            title: 'id',
            slotName: 'id',
            align: 'center',
          },
        ]"
        :data="table.allRow"
        :bordered="false"
        table-layout-fixed
      >
        <template #img="{ record }">
          <Upload v-model="record.img" :limit="1" />
        </template>
        <template #price="{ record }">
          <a-input-number v-model="record.price" :min="0" />
        </template>
        <template #stock="{ record }">
          <a-input-number v-model="record.stock" :min="0" />
        </template>
        <template #id="{ record }">
          <a-button type="text" @click="table.allSet"> 批量设置 </a-button>
          <a-button type="text" @click="table.allReset"> 重置 </a-button>
        </template>
      </a-table>
    </a-form-item>
    <a-form-item label="规格设置">
      <a-table
        row-key="id"
        :columns="table.columns"
        :data="table.data"
        :bordered="false"
        table-layout-fixed
        :pagination="false"
      >
        <template #img="{ record }">
          <Upload v-model="record.img" :limit="1" />
        </template>
        <template #price="{ record }">
          <a-input-number v-model="record.price" :min="0" />
        </template>
        <template #original_price="{ record }">
          <a-input-number v-model="record.original_price" :min="0" />
        </template>
        <template #stock="{ record }">
          <a-input-number v-model="record.stock" :min="0" />
        </template>
      </a-table>
    </a-form-item>
  </div>
</template>

<script setup>
  import { ref, nextTick, reactive, computed, watch } from 'vue';
  import { v4 as uuidv4 } from 'uuid';

  const emits = defineEmits(['update:modelValue']);
  const props = defineProps({
    // modelValue: {
    //   type: String,
    //   default: ``,
    // },
    modelValue: [],
    model: Object,
    arr: [],
  });
  const column = () => [
    {
      title: '图片',
      dataIndex: 'img',
      slotName: 'img',
      align: 'center',
      defaultValue: '',
    },
    {
      title: '积分',
      dataIndex: 'price',
      slotName: 'price',
      align: 'center',
      defaultValue: 0,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      slotName: 'stock',
      align: 'center',
      defaultValue: 0,
    },
  ];
  const getAllRow = () => [
    {
      img: ``,
      price: 0,
      stock: 0,
    },
  ];
  const table = reactive({
    allSet() {
      table.data.forEach((row) => {
        row['img'] = table.allRow[0].img;
        row['price'] = table.allRow[0].price;
        row['stock'] = table.allRow[0].stock;
      });
    },
    allReset() {
      table.allRow = getAllRow();
    },
    allColumns: column(),
    allRow: getAllRow(),
    create() {
      const arr = props.modelValue.filter((v) => v.name && v.value.length);
      let record = [];
      arr.forEach((item, index, ar) => {
        if (ar.length > 1) {
          if (index < ar.length - 1) {
            item.value.forEach((tag) => {
              const row = ar[index + 1].value.map((tag_) => ({
                [item.name]: tag,
                [ar[index + 1].name]: tag_,
                id: uuidv4(),
              }));
              record = [...record, ...row];
            });
          }
        } else {
          item.value.forEach((tag) => {
            record = [
              ...record,
              {
                [item.name]: tag,
                id: uuidv4(),
              },
            ];
          });
        }
      });

      const cloumns = table.columns.map(({ dataIndex, defaultValue }) => ({
        dataIndex,
        defaultValue,
      }));
      // const data = record.map((item, index) => {
      //   for (const key in table.columns) {
      //     let columns = table.columns[key];
      //     if (!columns?.dataIndex) continue;
      //     if (columns.dataIndex in item) {
      //       item[columns.dataIndex] = item[columns.dataIndex];
      //     } else {
      //       item[columns.dataIndex] = columns.defaultValue;
      //     }
      //   }
      //   return item;
      // });
      // console.error(data);
      let obj = {};
      cloumns
        .filter(({ defaultValue }) => defaultValue !== undefined)
        .map(({ dataIndex, defaultValue }) => ({ [dataIndex]: defaultValue }))
        .forEach((item) => {
          obj = { ...obj, ...item };
        });

      table.data = record.map((row, i) => {
        const is = props.arr[i] ? props.arr[i] : obj;
        const newRow = { ...row, ...is };
        return newRow;
      });
    },
    columns: computed(() => [
      ...props.modelValue
        .filter((v) => v.name && v.value.length)
        .map((item) => ({
          title: item.name,
          dataIndex: item.name,
          slotName: item.name,
          align: 'center',
        })),
      ...column(),
      // {
      //   title: '操作',
      //   slotName: 'id',
      //   align: 'center',
      // },
    ]),
    data: props.arr.map((item) => ({ ...item, id: uuidv4() })),
  });
  watch(
    () => table.data,
    (newData) => {
      emits('update:arr', newData);
      console.error(JSON.stringify(newData));
    },
    { deep: true }
  );

  const add = () => {
    emits('update:modelValue', [...props.modelValue, { ...props.model }]);
  };

  const del = (index) => {
    const v = [...props.modelValue];
    v.splice(index, 1);
    emits('update:modelValue', v);
  };

  const inputRef = ref(null);
  const showInput = ref(true);
  const inputVal = ref('');

  const defaultState = (model) =>
    model.map((item) => ({
      showInput: false,
      inputVal: '',
    }));
  const state = ref(defaultState(props.modelValue));
  watch(
    () => props.modelValue,
    (newModelValue) => {
      state.value = defaultState(newModelValue);
    }
  );
  const handleEdit = (index) => {
    state.value[index].showInput = true;

    nextTick(() => {
      if (inputRef.value[index]) {
        inputRef.value[index].focus();
      }
    });
  };

  const handleAdd = (index, val) => {
    if (state.value[index].inputVal) {
      state.value[index].inputVal = '';
      const v = [...props.modelValue];
      v[index].value = [...v[index].value, val];
      console.log(v[index].value);
      emits('update:modelValue', v);
    }
    state.value[index].showInput = false;
  };

  const handleRemove = (key, item) => {
    item.value = item.value.filter((tag) => tag !== key);
  };
</script>

<style lang="scss" scoped></style>
